<?php
namespace Core;

class Event
{

    private $data = [];

    public function listen($event, $callback, $once = false)
    {
        if(is_callable($callback)){
            $this->data[$event][] = ['callback' => $callback, 'once' => $once];
        }
    }

    public function one($event, $callback)
    {
        $this->listen($event, $callback, true);
    }

    public function remove($event, $index = null)
    {
        if(is_null($index)){
            unset($this->data[$event]);
        }
        else{
            unset($this->data[$event][$index]);
        }
    }

    public function trigger($event, $data = null)
    {
        if(isset($this->data[$event])){
            $list = $this->data[$event];
            foreach($list as $index => $listen){
                $callback = $listen['callback'];
                if($listen['once']){
                    $this->remove($event, $index);
                }
                if(is_null($data)){
                    call_user_func($callback);
                }
                else{
                    call_user_func($callback, $data);
                }
            }
        }
    }

}